import 'package:flutter/material.dart';

// 路由
import 'package:chat_client/router/router.dart';
import 'package:chat_client/screens/mobile/contact/contact_page.dart';
import 'package:chat_client/screens/mobile/menu/black_list.dart';
// 仓库
import 'package:chat_client/models/apply_model.dart';
import 'package:chat_client/models/user_model.dart';
import 'package:chat_client/models/contact_model.dart';
// 服务
import 'package:chat_client/services/user_service.dart';
import 'package:chat_client/providers/contact_provider.dart';
import 'package:chat_client/services/contact_service.dart';
// 组件
import 'package:chat_client/widgets/c_loading.dart';
import 'package:chat_client/widgets/c_input_dialog.dart';
//工具
import 'package:chat_client/utils/current_limiting.dart';
import 'package:chat_client/utils/show_messae.dart';
// 枚举
import 'package:chat_client/screens/mobile/menu/aplly_list.dart';
import 'package:chat_client/screens/mobile/menu/send_allpy_page.dart';
import 'package:provider/provider.dart';
import 'package:chat_client/enums/contact_enum.dart';

class ApplicationProvider extends ChangeNotifier {
  final ContactService _contactService = ContactService.instance;
  final UserService _userService = UserService.instance;

  final TextEditingController _searchController = TextEditingController();
  late final (DebouncedFunction<void>, CancelDebounce) _debounceShowSearchBtu;
  late List<Apply> _applicationList;
  late List<Contact> _blackList;

  // 搜索文字
  String _searchText = '';
  // 是否展示搜索按钮
  bool _hasText = false;
  //
  String get searchText => _searchText;
  bool get showSearchBtu => _hasText;
  TextEditingController get searchController => _searchController;
  List<Apply> get applicationList => _applicationList;
  List<Contact> get blackList => _blackList;

  ApplicationProvider() {
    _applicationList = _contactService.getLocalFriendRequestList();
    _blackList = _contactService.getLocalBlockList();
    notifyListeners();
    // 在构造函数中初始化防抖函数
    _debounceShowSearchBtu = debounce<void>(
      (_) {
        _hasText = _searchController.text.isNotEmpty;
        _searchText = _searchController.text;
        notifyListeners();
      },
      duration: const Duration(milliseconds: 500),
    );
  }

  @override
  void dispose() {
    _searchController.dispose();
    final (_, cancel) = _debounceShowSearchBtu;
    cancel(); // 取消防抖计时器
    super.dispose();
  }

  // 搜索条动态展示（带防抖）
  Future<void> handleSearchInput() async {
    final (debounced, cancel) = _debounceShowSearchBtu;
    debounced(null);
  }

  // 搜索新朋友
  Future<void> handleSearch(BuildContext context) async {
    final searchText = _searchController.text.trim();
    if (searchText.isEmpty) return;

    Loading.show(message: "正在搜索...");

    try {
      final result = await _contactService.searchUser(searchText);
      final status = result['status'];
      final User user = User.fromJson(result['user']);

      // 如果已经是好友，转跳好友详情页面
      if (status != null && status == ContactStatus.friend.value) {
        final Contact contact = _contactService.getLocalContact(user.userId);
        RouteManager.navigateToWidget(ContactScreen(contact: contact));
        return;
      }

      final String infoSource = result['source'];

      // 不是好友，转跳好友申请页面
      RouteManager.navigateToWidget(ContactPreviewScreen(
        user: user,
        infoSource: infoSource,
        isBlacked: status == ContactStatus.black.value,
      ));
    } catch (e) {
      popError(e.toString(), '查找失败');
    } finally {
      Loading.hide();
    }
  }

  // 发送好友申请
  openDialogToSendApply({
    required String userId,
    required String nickname,
  }) async {
    // 发送申请
    sendApply(String message) async {
      try {
        Loading.show();

        final resMsg = await _contactService.sendFriendRequest(
          applyInfo: message,
          userId: userId,
        );

        popMessage(resMsg);
        // 更新列表和UI
        _applicationList = _contactService.getLocalFriendRequestList();
        notifyListeners();

        navBack();
        _refreshContactList();
      } catch (e) {
        popError(e.toString(), '发送失败');
      } finally {
        Loading.hide();
      }
    }

    final User user = _userService.getLocalUserInfo();
    // 打开弹窗
    showDialog(
      context: navigatorKey.currentContext!,
      builder: (context) => DialogWithInput(
        title: '发送好友申请',
        subtitle: 'to 用户',
        nickname: nickname,
        initMessage: '你好我是${user.nickname}!',
        onSubmit: sendApply,
      ),
    );
  }

  /// 处理好友申请
  Future<void> handleFriendRequest(
    String senderId,
    bool isAccepted,
    String? applyInfo,
  ) async {
    Loading.show();
    try {
      String success = await _contactService.handleFriendRequest(
        senderId,
        isAccepted,
        applyInfo,
      );
      _applicationList = _contactService.getLocalFriendRequestList();
      notifyListeners(); // 刷新UI

      popMessage(success);

      if (isAccepted) _refreshContactList();
    } catch (e) {
      popError(e.toString(), '处理失败');
    } finally {
      Loading.hide();
    }
  }

  // 处理用户拉黑
  Future<void> handleBlackUser(String senderId, bool unBlacked) async {
    Loading.show();
    try {
      // 处理拉黑
      String success =
          await _contactService.handleBlackUser(senderId, unBlacked);
      popMessage(success);
      // 刷新列表
      _applicationList = _contactService.getLocalFriendRequestList();
      _blackList = _contactService.getLocalBlockList();
      // 刷新UI
      notifyListeners();
    } catch (e) {
      popError(e.toString(), '处理失败');
    } finally {
      Loading.hide();
    }
  }

  /// 路由转跳
  navToNewFriends() {
    RouteManager.navigateToWidget(FriendApplicationScreen());
  }

  navToBlockList() {
    RouteManager.navigateToWidget(BlockListScreen());
  }

  navToWidget(Widget page) {
    RouteManager.navigateToWidget(page);
  }

  navBack() {
    RouteManager.goBack();
  }

  /// 刷新联系人列表
  void _refreshContactList() {
    final context = navigatorKey.currentContext;
    if (context != null) {
      context.read<ContactProvider>().refreshContacts();
    }
  }

  // 暴露其它单例服务，用于刷新UI
  refreshApplications() {
    _applicationList = _contactService.getLocalFriendRequestList();
    notifyListeners();
  }
}
